package com.jasiri.project.ui.process.page

import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.jasiri.project.R
import com.jasiri.project.databinding.PageOcrDriverLicenseBinding
import com.jasiri.project.pro.ProFragment
import com.jasiri.project.ui.process.activity.CameraOcrActivity
import com.jasiri.project.ui.process.activity.ProcessActivity
import com.jasiri.project.utils.dialog.PhotoDialog
import com.jasiri.project.utils.dialog.SubmitSuccessDialog
import com.jasiri.project.utils.event.EventType
import com.jasiri.project.utils.event.track.TrackEventManager
import com.jasiri.project.utils.gilde.ImageUtil
import com.jasiri.project.utils.http.AppUrls
import com.jasiri.project.utils.http.AppUrls.addCommonParams
import com.jasiri.project.utils.http.IHttpCallback
import com.jasiri.project.utils.imagecovert.ImageConvert
import com.jasiri.project.utils.log.HHLog
import com.jasiri.lib.baseadapter.JasiriBaseAdapterUtil.getColor
import com.jasiri.project.app.App
import com.jasiri.project.lib.dev.JasiriSysDataHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import org.json.JSONObject
import java.io.File

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/19 18:22
 * @Annotation：流程 - 证件照 - 驾驶证信息
 */
class OcrDriverLicensePage: ProFragment(), CoroutineScope by MainScope() {
    private var _binding: PageOcrDriverLicenseBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var isFront = false//是否是正面
    //正面照
    private var imgFrontUrl = ""
    //背面照
    private var imgBackUrl = ""
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>
    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageOcrDriverLicenseBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        rootViewBinding.containerLayout.setBackgroundColor(requireContext().getColor(R.color.transparent))
        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                HHLog.e("uri.path>>>>>>>>>>>>>>${uri.path}")
                ImageConvert.covert(context = requireContext(), uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        if (isFront){
                            ImageUtil.instance?.loadImageUrl(requireContext(),_binding?.imgFront,localPath)
                        } else {
                            ImageUtil.instance?.loadImageUrl(requireContext(),_binding?.imgBack,localPath)
                        }
                        uploadImageAction(localPath)
                    }
                }


            } else {
                HHLog.e("No media selected")
            }
        }
    }

    override fun initListener() {
        //驾驶证正面
        _binding?.frontLayout?.setOnClickListener {
//            if (imgFrontUrl .isNotEmpty()){
//                return@setOnClickListener
//            }
            isFront = true
            showPhotoDialog("DriverLicense Front")
        }

        //驾驶证反面
        _binding?.backLayout?.setOnClickListener {
//            if (imgBackUrl.isNotEmpty()){
//                return@setOnClickListener
//            }
            isFront = false
            showPhotoDialog("DriverLicense Back")
        }
        //下一步
        _binding?.btnNext?.setOnClickListener {
            if (imgFrontUrl.isEmpty() || imgBackUrl.isEmpty()){
                showToast(getString(R.string.tips_submit_error))
                return@setOnClickListener
            }

            val params = JSONObject().addCommonParams().apply {
                put("path", AppUrls.PATH.OCR_INFO)
                put("cardType","DRIVING")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("cardImgUrl",imgFrontUrl)//证件图片正面
                put("cardBackImgUrl",imgBackUrl)//证件图片反面
            }
            showDrivingLicenseSubmitDeleteInformationTipsDialog(params)

            TrackEventManager.trackEventNow(EventType.CLICK.CLICK_STEP_OCR_DRIVERLICENSE_NEXT,"")
            //上报位置和陀螺仪数据
            JasiriSysDataHelper.onCheckSubmitDataByTypes(App.instance(), arrayListOf("T11","T12"),"Drive License Page")
        }
    }

    override fun initData() {
        addEvent(String.format(EventType.PAGE.PAGE_STEP_OCR_XX_START,"DriverLicense"),"")

        val showApprovedKey1 = getString(R.string.process_face_submit_approved_tips_over)
        val showApprovedKey2 = getString(R.string.process_face_submit_approved_tips_days)
        val showApprovedText = String.format(getString(R.string.process_face_submit_approved_tips),showApprovedKey1,showApprovedKey2)
        val startApprovedIndex1 = showApprovedText.indexOf(showApprovedKey1)
        val startApprovedIndex2 = showApprovedText.indexOf(showApprovedKey2)
        val approvedTipsSpannable = SpannableString(showApprovedText)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF00CB48)), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF00CB48)), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textDrivingLicenseApproved?.text = approvedTipsSpannable
    }

    /**
     * 提交成功提示
     */
    private fun showDrivingLicenseSubmitDeleteInformationTipsDialog(params: JSONObject){
        val sendSuccessDialog = SubmitSuccessDialog(requireContext())
        sendSuccessDialog.setCancelable(false)
        sendSuccessDialog.setCanceledOnTouchOutside(false)
        sendSuccessDialog.show()
        sendSuccessDialog.showSubmitSuccess(getString(R.string.process_face_submit_success_tips))
        Handler(Looper.getMainLooper()).postDelayed({
            sendSuccessDialog.dismiss()
            val act = context as ProcessActivity
            act.submitAction(params)
        },1500)
    }

    /**
     * 相机、相册选择
     */
    private fun showPhotoDialog(eventRemark: String){
        val photoDialog = PhotoDialog(context,eventRemark,object : PhotoDialog.IDialogCallback{
            override fun openCamera() {
                addEvent(EventType.CLICK.CLICK_CAMERA,eventRemark)
                onOpenCamera()
            }
            override fun openAlbum() {
                addEvent(EventType.CLICK.CLICK_ALBUM,eventRemark)
                onOpenAlbum()
            }
        })
        photoDialog.show()
    }

    /**
     * 拍照
     */
    private val takePhotoResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                HHLog.e(">>>>>>onActivityResult: data = " + result.data)
                val imgPath = result.data?.getStringExtra("imgLocalPath")
                if (imgPath != null){
                    if (isFront){
                        ImageUtil.instance?.loadImageUrl(context,_binding?.imgFront,imgPath)
                    } else {
                        ImageUtil.instance?.loadImageUrl(context,_binding?.imgBack,imgPath)
                    }
                    uploadImageAction(imgPath)
                }
            }
        }
    }

    /**
     * 打开相机
     */
    private fun onOpenCamera(){
        val intent = Intent(context, CameraOcrActivity::class.java)
        takePhotoResultLauncher.launch(intent)
    }

    /**
     * 打开相册
     */
    private fun onOpenAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 根据uri获取文件路径
     */
    private fun getRealPathFromURI(contentURI: Uri): String? {
        val result: String?
        val cursor = requireContext().contentResolver.query(contentURI, null, null, null, null)
        if (cursor == null) {
            result = contentURI.path
        } else {
            cursor.moveToFirst()
            val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
            result = cursor.getString(idx)
            cursor.close()
        }
        return result
    }

    /**
     * 上传图片
     */
    private fun uploadImageAction(imgPath: String){
        showLoading()
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.FILE)
        uploadFileAction(httpUrl, File(imgPath),object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                data.optJSONObject("obj")?.let {
                    val imgUrl = it.optString("url")
                    if (isFront){
                        imgFrontUrl = imgUrl
                        addEvent(EventType.CLICK.CLICK_STEP_OCR_UPLOAD_USE_PHOTO, "DriverLicense Front ：$imgUrl")
                    } else {
                        imgBackUrl = imgUrl
                        addEvent(EventType.CLICK.CLICK_STEP_OCR_UPLOAD_USE_PHOTO, "DriverLicense Back ：$imgUrl")
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(String.format(EventType.PAGE.PAGE_STEP_OCR_XX_END,"DriverLicense"),"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}